﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using ZX.Web.UI.Controls;
using ZX.EHR.ResumeParseLib;
using System.Configuration;
using DevExpress.Web.ASPxUploadControl;
using System.IO;
using DevExpress.Web.ASPxClasses.Internal;
using System.Web.Caching;
using ZX.EHR.Library;
using System.Data;
using ZX.DAL.DBExtend;
using ZX.Aspose;
using log4net;

namespace ZX.WebApp.EHR
{
    public partial class hrImportInsurance : BasePage
    {
        static string resFileName = "";
        string flag = "", importType = "";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (IsPostBack)
            {
                UploadControl.ShowProgressPanel = true;
            }
            flag = this.GetStringFromQueryString("flag", "");
            importType = this.GetStringFromQueryString("importType", "");
            if (flag.Trim() == "save")
            {
                this.SaveData();
            }
        }

        protected void UploadControl_FileUploadComplete(object sender, FileUploadCompleteEventArgs e)
        {
            try
            {
                e.CallbackData = SavePostedFiles(e.UploadedFile);
            }
            catch (Exception ex)
            {
                e.IsValid = false;
                e.ErrorText = ex.Message;
            }
        }

        string SavePostedFiles(UploadedFile uploadedFile)
        {
            try
            {
                if (!uploadedFile.IsValid)
                    return string.Empty;

                FileInfo fileInfo = new FileInfo(uploadedFile.FileName);
                string path = Request.PhysicalApplicationPath + "upload\\EHR\\";
                if (!System.IO.Directory.Exists(path))
                {
                    System.IO.Directory.CreateDirectory(path);
                }
                resFileName = path + fileInfo.Name;
                uploadedFile.SaveAs(resFileName);

                RemoveFileWithDelay(uploadedFile.FileName, resFileName, 5);
                string fileLabel = fileInfo.Name;
                string fileLength = uploadedFile.ContentLength / 1024 + "K";
                return string.Format("{0} ({1})|{2}", fileLabel, fileLength, fileInfo.Name);
            }
            catch (Exception ex)
            {
                return "";
            }
        }



        static void RemoveFileWithDelay(string key, string fullPath, int delay)
        {
            if (HttpUtils.GetCache()[key] == null)
            {
                DateTime absoluteExpiration = DateTime.Now.Add(new TimeSpan(0, delay, 0));
                HttpUtils.GetCache().Insert(key, fullPath, null, absoluteExpiration,
                    Cache.NoSlidingExpiration, CacheItemPriority.NotRemovable, new CacheItemRemovedCallback(RemovedCallback));
            }
        }
        static void RemovedCallback(string key, object value, CacheItemRemovedReason reason)
        {
            if (File.Exists(value.ToString()))
                File.Delete(value.ToString());
        }

        protected void SaveData()
        {
            /// <summary>
            /// 所有上传五险一金数据
            /// </summary>
            IList<DataTable> lstImportData = null;
            try
            {
                //读取EXCEL
                //string resFileName = Request.PhysicalApplicationPath + "upload/EHR/" + fileName;
                if (resFileName != "")
                {
                    lstImportData = new List<DataTable>();
                    DataTable dtExcel = DbSql.ReadEcxel(resFileName, 1);

                    //ImportCell importCell = new ImportCell();
                    //importCell.FilePath = resFileName;

                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("身份证号", "身份证号"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("个人电脑号", "个人电脑号"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("年月", "年月"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("应收合计", "应收合计"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("个人合计", "个人合计"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("单位合计", "单位合计"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("工资", "工资"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("养老个人交", "养老个人交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("养老单位交", "养老单位交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("医疗个人交", "医疗个人交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("医疗单位交", "医疗单位交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("工伤缴费工资", "工伤缴费工资"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("工伤单位交", "工伤单位交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("失业参保情况", "失业参保情况"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("生育单位交", "生育单位交"));
                    //importCell.LstImportColumnConfig.Add(new ImportColumnConfig("意外单位交", "意外单位交"));
                    //DataTable dtExcel = importCell.ImportToTable("Sheet1");

                    //DataTable dtExcel = importCell.GetSheetDataToDataSet().Tables[0];

                    if (dtExcel != null && dtExcel.Rows.Count > 0)
                    {
                        lstImportData.Add(dtExcel);
                    }
                    if (lstImportData.Count > 0)
                    {
                        DbSql dbsql = new DbSql();
                        string insertSql = "insert into xzEmpInsurance([ID],[EmployeeID],[YearMonth]) values(NEWID(),'{0}','{1}')";
                        string updateSql = @"UPDATE xzEmpInsurance SET [Laborage] ={0} ,[EmpEndowment] ={1},[CoEndowment] ={2} ,[CompoLaborage] ={3} ,[CoCompo] = {4},
                                                   [Unemployment] ='{5}' ,[CoProcreate] = {6},[EmpHospitalization] = {7} ,[CoHospitalization] ={8},
                                                   AccountReceivable={10},EmpAccountReceivable={11},CoAccountReceivable={12},[CoAccidental]={13},
                                                    [EndowmentLaborage]='{14}',[HospitalizationLaborage]='{15}',[UnemploymentLaborage]='{16}',
                                                    [EmpUnemployment]='{17}',[CoUnemployment]='{18}',[ProcreateLaborage]='{19}'
                                                    where ID='{9}' ";

                        foreach (DataTable dt in lstImportData)
                        {
                            foreach (DataRow dr in dt.Rows)
                            {
                                string IDCardNO = dr["身份证号"].ToString().Trim();
                                if (IDCardNO == "")
                                {
                                    continue;
                                }
                                string socialInsuranceNO = dr["个人电脑号"].ToString().Trim();
                                Dictionary<string, string> dicEmpInfo = GetEmpInfos(IDCardNO, socialInsuranceNO);
                                if (dicEmpInfo.Count > 0)
                                {
                                    string employeeID = dicEmpInfo["EmployeeID"];
                                    string employeeName = dicEmpInfo["EmployeeName"];
                                    string employeeCode = dicEmpInfo["EmployeeCode"];
                                    string yearMonth = dr["年月"].ToString();

                                    decimal accountReceivable = 0, empaccountReceivable = 0, coaccountReceivable = 0, laborage = 0, CompoLaborage = 0, empEndowment = 0, coEndowment = 0;
                                    decimal coCompo = 0, coProcreate = 0;
                                    decimal empHospitalization = 0, coHospitalization = 0, coAccidental = 0;
                                    decimal endowmentLaborage = 0, hospitalizationLaborage = 0, procreateLaborage = 0, unemploymentLaborage = 0, empUnemployment = 0, coUnemployment = 0;
                                    string id = "", Unemployment = "";

                                    decimal.TryParse(dr["应收合计"].ToString(), out accountReceivable);
                                    decimal.TryParse(dr["个人合计"].ToString(), out empaccountReceivable);
                                    decimal.TryParse(dr["单位合计"].ToString(), out coaccountReceivable);
                                    //decimal.TryParse(dr["工资"].ToString(), out laborage);

                                    decimal.TryParse(dr["养老缴费基数"].ToString(), out endowmentLaborage);
                                    decimal.TryParse(dr["养老个人交"].ToString(), out empEndowment);
                                    decimal.TryParse(dr["养老单位交"].ToString(), out coEndowment);

                                    decimal.TryParse(dr["医疗缴费基数"].ToString(), out hospitalizationLaborage);
                                    decimal.TryParse(dr["医疗个人交"].ToString(), out empHospitalization);
                                    decimal.TryParse(dr["医疗单位交"].ToString(), out coHospitalization);

                                    decimal.TryParse(dr["工伤缴费基数"].ToString(), out CompoLaborage);
                                    decimal.TryParse(dr["工伤单位交"].ToString(), out coCompo);

                                    //Unemployment = dr["失业参保情况"].ToString();
                                    decimal.TryParse(dr["失业缴费基数"].ToString(), out unemploymentLaborage);
                                    decimal.TryParse(dr["失业个人交"].ToString(), out empUnemployment);
                                    decimal.TryParse(dr["失业单位交"].ToString(), out coUnemployment);

                                    decimal.TryParse(dr["生育缴费基数"].ToString(), out procreateLaborage);
                                    decimal.TryParse(dr["生育单位交"].ToString(), out coProcreate);

                                    //decimal.TryParse(dr["意外单位交"].ToString(), out coAccidental);

                                    //首先判断当月是否有此员工记录，无则写入基本信息
                                    id = IsExistsData(employeeID, yearMonth);
                                    if (id == "")
                                    {
                                        dbsql.ExecuteSql(string.Format(insertSql, employeeID, yearMonth));
                                        id = IsExistsData(employeeID, yearMonth);
                                    }
                                    ////更新
                                    // [Laborage] ={0} ,[EmpEndowment] ={1},[CoEndowment] ={2} ,[CompoLaborage] ={3} ,[CoCompo] = {4}, [Unemployment] ={5} ,[CoProcreate] = {6},[EmpHospitalization] = {7} ,[CoHospitalization] ={8}  AccountReceivable={10},EmpAccountReceivable={11},CoAccountReceivable={12},[CoAccidental]={13} where ID='{9}' 
                                    dbsql.ExecuteSql(string.Format(updateSql, laborage, empEndowment, coEndowment, CompoLaborage, coCompo, Unemployment, coProcreate, empHospitalization, coHospitalization, id, accountReceivable, empaccountReceivable, coaccountReceivable, coAccidental, endowmentLaborage, hospitalizationLaborage, unemploymentLaborage, empUnemployment, coUnemployment, procreateLaborage));
                                }
                            }
                        }
                        HttpContext.Current.Response.Write("1");
                    }
                    else
                    {
                        HttpContext.Current.Response.Write("读取EXCEL为空,请检查文件,可能Sheet未命名为Sheet1或没有数据!");
                    }
                }
                else
                {
                    HttpContext.Current.Response.Write("文件未上传");//文件未上传
                }
            }
            catch (Exception ex)
            {
                HttpContext.Current.Response.Write(ex.Message);//出错了
                throw;
                //var logger = LogManager.GetLogger(GetType());
                //logger.Error(ex.Message, ex);
            }
            finally
            {
                if (lstImportData != null)
                {
                    lstImportData.Clear();
                }
                resFileName = "";
            }
        }

        /// <summary>
        /// 根据导入的个人身份证号码，匹配员工信息
        /// </summary>
        /// <param name="IDCardNO">身份证号码</param>
        /// <param name="socialInsuranceNO">社保电脑号码</param>
        /// <returns></returns>
        protected Dictionary<string, string> GetEmpInfos(string IDCardNO,string socialInsuranceNO)
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();
            hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("IDCardNO='{0}'", IDCardNO);
            ZX.EHR.Library.hrEmployee hrEmployee = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            if (hrEmployee != null)
            {
                dic.Add("EmployeeID", hrEmployee.ID.ToString());
                dic.Add("EmployeeCode", hrEmployee.EmployeeCode);
                dic.Add("EmployeeName", hrEmployee.CName);

                //更新社保电脑号
                if (hrEmployee.SocialInsuranceNO.Trim() != socialInsuranceNO)
                {
                    UpdateEmpSocialInsuranceNO(hrEmployee.ID.ToString(), socialInsuranceNO);
                }
            }
            return dic;
        }

        /// <summary>
        /// 员工导入月份的数据是否已经存在了
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="YearMonth"></param>
        /// <returns></returns>
        protected string IsExistsData(string employeeId, string YearMonth)
        {
            string id = "";
            xzEmpInsurance instance = ZX.Common.Globals.getEntity("xzEmpInsurance") as xzEmpInsurance;
            ZX.BLL.Extend.BaseBussnies bll = new ZX.BLL.Extend.BaseBussnies(instance);
            string condition = string.Format("EmployeeID='{0}' and YearMonth='{1}' ", employeeId, YearMonth);
            ZX.EHR.Library.xzEmpInsurance xzEmpInsurance = bll.GetEntityByCondition(condition) as ZX.EHR.Library.xzEmpInsurance;
            if (xzEmpInsurance != null)
            {
                id = xzEmpInsurance.ID.ToString();
            }
            return id;
        }

        /// <summary>
        /// 更新员工社保电脑号
        /// </summary>
        /// <param name="employeeId"></param>
        /// <param name="socialInsuranceNO"></param>
        /// <returns></returns>
        protected bool UpdateEmpSocialInsuranceNO(string employeeId, string socialInsuranceNO)
        {
            bool result = false;
            DbSql dbSq= new DbSql();
            string sql = string.Format("Update hrEmployee Set  SocialInsuranceNO='{0}' where ID='{1}' ", socialInsuranceNO, employeeId);
            result = dbSq.ExecuteSql(sql) > 0;

            //hrEmployee instance = ZX.Common.Globals.getEntity("hrEmployee") as hrEmployee;
            //ZX.BLL.Extend.BaseBussnies hrBll = new ZX.BLL.Extend.BaseBussnies(instance);
            //string condition = string.Format("id='{0}'", employeeId);
            //ZX.EHR.Library.hrEmployee hrupdate = hrBll.GetEntityByCondition(condition) as ZX.EHR.Library.hrEmployee;
            //hrupdate.SocialInsuranceNO = socialInsuranceNO;
            //result = hrBll.Update(hrupdate);
            return result;


        }
    }
}